package com.chixing.listener;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.chixing.entity.UserMessage;
import com.chixing.mapper.UserMessageMapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
import java.util.List;


/**
 * 监听redis中过期的消息列表，在数据库中将他们的消息状态改为 “ EXPIRED=过期未送达 ”
 */
@Component
public class RedisKeyExpiredListener extends KeyExpirationEventMessageListener {

    @Autowired
    private UserMessageMapper userMessageMapper;

    @Autowired
    private ObjectMapper objectMapper; // JSON 解析

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    public RedisKeyExpiredListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }

    /**
     * Redis key 过期事件监听
     * 处理用户离线消息过期，将对应 user_message 记录标记为 EXPIRED
     */
    @Override
    public void onMessage(Message message, byte[] pattern) {
        try {
            String expiredKey = message.toString();
            System.out.println("检测到 Redis Key 过期:"+ expiredKey);

            // 判断是否是我们存离线消息的 key
            if (expiredKey.startsWith("offline_user")) {
                // 提取用户ID
                String userIdStr = expiredKey.replace("offline_user", "");
                Long userId = Long.parseLong(userIdStr);

                // **注意**：Key 已过期，Redis list 已经被删除，无法再获取到 value
                // 所以直接从数据库查该用户未送达消息
                List<Long> offlineMsgIds = userMessageMapper.selectUnreadIdsByUserId(userId);

                if (offlineMsgIds != null && !offlineMsgIds.isEmpty()) {
                    LocalDateTime now = LocalDateTime.now();
                    for (Long id : offlineMsgIds) {
                        //修改消息的状态为 “EXPIRED=过期未送达”
                        userMessageMapper.updateExpiredStatusById(id, now);
                        System.out.println(" 用户 "+userId+" 消息 {} 标记为 EXPIRED"+ id);
                    }
                } else {
                    System.out.println(" 用户 "+userId+" 没有未送达的离线消息，无需处理");
                }
            }

        } catch (Exception e) {
            System.out.println("处理 Redis Key 过期事件异常"+ e);
        }
    }
}
